package com.jwx.mycar.service.impl;

import com.jwx.mycar.entity.po.User;
import com.jwx.mycar.entity.vo.ResultVo;
import com.jwx.mycar.mapper.StatMapper;
import com.jwx.mycar.mapper.UserMapper;
import com.jwx.mycar.service.UserService;
import com.jwx.mycar.utils.KeyUtil;
import com.jwx.mycar.utils.ResultVOUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.mail.javamail.JavaMailSender;
import org.springframework.stereotype.Service;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;


@Service
public class UserServiceImpl implements UserService {
    @Autowired
    private UserMapper userMapper;
    @Autowired
    private ResultVOUtil resultVOUtil;

    @Autowired
    StatMapper statMapper;


    @Autowired
    private RedisTemplate<Object, Object> redisTemplate;
    /**
     * 根据账号和密码登录
     * @param  email,password
     * @return ResultVo
     */

    @Override
    public ResultVo login(String email, String password, HttpServletRequest request, HttpServletResponse response) throws IOException {
        response.setContentType("text/html;charset=utf-8");
        response.setCharacterEncoding("utf-8");
        try {
            String password1 = userMapper.selectPasswordByEmail(email);
            String username = userMapper.selectUsernameByEmail(email);
            if (password1.equals(password)) {
                User user = userMapper.selectUserByUsername(username);
                request.getSession().setAttribute("user", user);//用户存入该用户的session 中
                return resultVOUtil.success("登录成功",user);
            } else
                return  resultVOUtil.fail("账号密码错误");
        }
        catch (Exception e){
            e.printStackTrace();
            return resultVOUtil.unkonwError("用户不存在");
        }
    }

    /**
     * 注册用户
     * @param  username,password,email
     * @return ResultVo
     */
    @Override
    public ResultVo register(String username, String password,String email,String code,HttpServletRequest request) {
        try {
            boolean isUserExist = userMapper.userExist(username);//判断用户是否存在
//            System.out.println(isUserExist);
            boolean isEmailExist = userMapper.emailExist(email);//判断邮箱是否已经被注册
//            System.out.println(isEmailExist);
            if (isUserExist) {
                return resultVOUtil.fail("该用户名已经存在，请重新输入");
            } else if (isEmailExist) {
                return resultVOUtil.fail("该邮箱已经被注册，换一个试试吧");
            } else if (!email.matches("\\w+([-+.]\\w+)*@\\w+([-.]\\w+)*\\.\\w+([-.]\\w+)*")) {//判断邮箱格式是否正确
                return resultVOUtil.fail("邮箱格式错误，请重新输入");
            } else {
                String imageCode = (String) redisTemplate.opsForValue().get(email);
//                System.out.println("获取主键email："+email);
//                System.out.println("获取value"+imageCode);
                if(imageCode==null){
                    return resultVOUtil.fail("请刷新验证码");
                }
                 else if(code.equalsIgnoreCase(imageCode)){
                    String id= KeyUtil.genUniqueKey();
                    userMapper.addUser(id,username,password,email);
                    return resultVOUtil.success("注册成功");
                }
                 else {
                     return resultVOUtil.fail("验证码错误");
                }
            }
            }
//                HttpSession session = request.getSession();
//
//                if (session.getAttribute("imageCode") == null) {
//                    return resultVOUtil.fail("请刷新验证码");
//
//                }
//                else  if (session.getAttribute("imageCode").toString().equalsIgnoreCase(code)) {
//                    {
//                        String id= KeyUtil.genUniqueKey();
//                        userMapper.addUser(id,username,password,email);
//                        return resultVOUtil.success("注册成功");
//
//                    }
//
//                }
//
//                return resultVOUtil.fail("验证码错误");
/**                Cookie[] cookies = request.getCookies();
            if (cookies != null) {
                for (Cookie cookie : cookies) {
                    if (cookie.getName().equals("sessionId")) {
                        String code1 = cookie.getValue();
                        if (code.equalsIgnoreCase(code1)) {
                            String id = KeyUtil.genUniqueKey();
                            userMapper.addUser(id, username, password, email);
                            return resultVOUtil.success("注册成功");
                        } else {
                            return resultVOUtil.fail("验证码错误");
                        }
                    }
                    else {
                        return resultVOUtil.fail("请刷新验证码");
                    }
                }
            }

            return resultVOUtil.fail("请刷新验证码");

        }
 */

        catch (Exception e){
            e.printStackTrace();
            return resultVOUtil.unkonwError();
        }
    }

    @Override
    public ResultVo resetPassword(String newPassword, String email, String code, HttpServletRequest request,HttpServletResponse response) {
        try {
            boolean isEmailExist = userMapper.emailExist(email);//判断邮箱是否已经被注册
            if (!isEmailExist) {
                return resultVOUtil.fail("用户不存在");
            }
            else {
                HttpSession session = request.getSession();
                System.out.println(session.getId());
                if (session.getAttribute("resetCode") == null) {
                    return resultVOUtil.fail("请刷新验证码");

                }
                else  if (session.getAttribute("resetCode").toString().equals(code)) {
                        {
                                userMapper.updateUser(email,newPassword);
                                return resultVOUtil.success("重置密码成功");

                        }

                    }

                return resultVOUtil.fail("验证码错误");
            }
        }
        catch ( Exception e){
            e.printStackTrace();
            return  resultVOUtil.unkonwError();
        }
    }

    @Override
    public boolean changePassword(String password, String newPassword, String email) {
       String password1 =  userMapper.selectPasswordByEmail(email);
       if(password.equals(password1)){
           return userMapper.updateUser(email,newPassword);
       }
       else {
           return false;
       }

    }

    @Override
    public int getAllUpCount(HttpServletRequest request) {
        HttpSession session = request.getSession();
        User user = (User) session.getAttribute("user");
        String userId = user.getUserId();
       int count =  statMapper.getAllUpCountByUserId(userId);
        return 0;
    }


}
